<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>商品类别管理</title>
    <link rel="stylesheet" href="plugins/layui/css/layui.css" media="all" />
    <link rel="stylesheet" href="css/comments.css" media="all">
    <link rel="stylesheet" href="css/treeTable.css">
    <style>
        #modifyForm,#addForm{
            padding: 20px 20px 0 0;
            display: none;
        }
        #modifyForm .layui-form-label,#addForm .layui-form-label{
            width: 110px;
        }
        @media screen and (max-width: 450px){
            #modifyForm .layui-form-item .layui-input-inline,#addForm .layui-form-item .layui-input-inline{
                margin-left: 140px;
            }
        }
        #modifyForm .layui-input-block,#addForm .layui-input-block{
            margin-left: 140px;
        }
        .layui-layer-page .layui-layer-content{
            overflow: unset!important;
        }
        .toolbarDemo{
            line-height: 30px;
            padding: 10px 15px;
            background-color: #f2f2f2;
            border: 1px solid #e6e6e6;
            border-bottom: unset;
        }
    </style>
</head>
<body>
    <div class="maincontainer">
        <div class="layui-card">
            <div class="layui-card-header layuiadmin-card-header-auto">
                <form id="queryForm" class="layui-form" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品类别</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input" placeholder="商品类别" maxlength="20">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="button" class="layui-btn"  lay-submit lay-filter="searchBth">查询</button>
                            <button type="reset" class="layui-btn layui-btn-primary" >重置</button>
                        </div>
                    </div>
                </form>
            </div>
            <div class="layui-card-body">
                <div class="toolbarDemo">
                    <button class="layui-btn layui-btn-sm categoryAdd">新增</button>
                </div>
                <table class="layui-hide" id="categoryTable" lay-filter="categoryTable"></table>
            </div>
        </div>
    </div>
    
    <div id="addForm">
        <form class="layui-form" action="" lay-filter="addForm">
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="redtext marginRight">*</span>商品类别：</label>
                <div class="layui-input-block">
                  <input type="text" name="categoryName" autocomplete="off" placeholder="请输入商品类别" class="layui-input" maxlength="20">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">父级节点：</label>
                <div class="layui-input-inline">
                    <select name="parentId" lay-filter="parentId">
                        <option value=""></option>
                    </select>
                </div>
            </div>
        </form>
    </div>
</body>

<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container toolbarDemo">
		<button class="layui-btn layui-btn-sm" lay-event="add">新增</button>
	</div>
</script>
<script type="text/javascript" src="plugins/layui/layui.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
    
    layui.config({
        base: 'plugins/layui/modules/',
    }).use(['http', 'table', 'form', 'laydate', 'treeTable'], function() {
        var http = layui.http,
            table = layui.table,
            form = layui.form,
            laydate = layui.laydate,
            treeTable = layui.treeTable;
        var excelList,currPage

        //时间
        laydate.render({
            elem: '#selectTime'
            ,theme: '#DCB982'
            ,range: "-"
        });
		
		// 筛选(前端处理)
		const rebuildData = (value, arr) => {
		  let newarr = [];
		  arr.forEach(element => {
            element.open = false
			if (element.categoryName.indexOf(value) > -1) {
			  newarr.push(element);
			} else {
			  if (element.childCategory && element.childCategory.length > 0) {
				const ab = rebuildData(value, element.childCategory);
				const obj = {
				  ...element,
				  childCategory: ab
				};
				if (ab && ab.length>0) {
				  newarr.push(obj);
				}
			  }
			}
		  });
		  return newarr;
		};
        
        // 父级节点查询
        function getAllC(parentId){
            http.get('admin/product/category/listAll',{
                page: 1,
                limit: 10,
                attachParentStatus: 1
            },function(res){
                if(res.code == 200){
                    var html = '<option value=""></option>';
                    var data = res.data;
                    for (var i = 0; i < data.length; i++) {
                        html += '<option value="' + data[i].id + '">' + data[i].categoryName + '</option>'
                    }
                    $('#addForm select[name=parentId]').html(html);
                    form.render('select');
                    $('#addForm select[name=parentId]').val(parentId?parentId:'')
                    form.render('select');
                }else{
                    layer.msg(res.msg)
                }
            })
        }

        // 商品类别列表
        var categoryTable;
        getTableData()
        function getTableData() {
            http.get('admin/product/category/listAllTree',{},function(res) {
                if(res.code == 200){
					var nameVague = $('input[name=name]').val();
                    var datalist = rebuildData(nameVague,res.data) // 根据查询条件筛选数据
                    datalist = setOpen(datalist)// 设置展开
					getTable(datalist) // 表格渲染
                }else{
                    layer.msg(res.msg)
                }
            })
        }
        // 设置展开
        function setOpen(datalist){
            var historyList = sessionStorage.getItem('xi-can-management-treeTable') // 展开的id列表
            if(historyList){
                historyList = JSON.parse(historyList)
                for(var i=0;i<historyList.length;i++){
                    for(var j=0;j<datalist.length;j++){
                        if(historyList[i] == datalist[j].id){
                            datalist[j].open = true
                        }
                    }
                }
            }
            return datalist
        }
        // 表格渲染
        function getTable(data) {
            categoryTable = treeTable.render({
                elem: '#categoryTable',
                data: data,
                tree: {
                    iconIndex:1
                },
                id: 'categoryTable',
                cols: [
                    {type: 'numbers', title: '序号',width: 60}
                    // {field:'id', title: '类别ID', align : 'center',width: 100}
                    ,{field:'categoryName', title: '商品类别', align : 'center'}
                    // ,{field:'parentCategoryName', title: '父级节点', align : 'center'}
                    ,{field:'', title: '操作', align : 'center',fixed: 'right',width: 230,
                        templet: function (d) {
                            var html = '';
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="modify" >修改</button>'
                            html += '<button type="button" class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" >删除</button>'
                            return html;
                        }
                    }
                ],
                style: 'margin-top:0;'
            });
            // categoryTable.expandAll(); //展开数据
        }
		
        //查询
        form.on('submit(searchBth)', function (data) {
            getTableData()
        })
		
		

        // table操作
        treeTable.on('tool(categoryTable)', function(obj){
            var data = obj.data;
            // console.log(data)
            if(obj.event=='modify'){
                // 修改
                $("#addForm .layui-form")[0].reset();
                getAllC(data.parentId)
                form.val('addForm',{
                    categoryName: data.categoryName
                })
                http.myOpen({
                    title:'修改类别',
                    content: $('#addForm'),
                    area:['500px','300px'],
                    btn:['确定','取消'],
                    btn1:function(index, layero){
                        http.post('admin/product/category/update',{
                            id: data.id,
                            categoryName: $('#addForm input[name=categoryName]').val(),
                            parentId: $('#addForm select[name=parentId]').val(),
                            openStatus: 1
                        },function(res){
                            if(res.code == 200){
                                layer.msg('操作成功')
                                layer.close(index)
                                getTableData()
                            }else{
                                layer.msg(res.msg)
                            }
                        })
                    }
                })
            }else if(obj.event=='del'){
                // 删除
                http.myOpen({
                    title:'提示',
                    content:'<p style="text-align:center;padding-top:20px">确认要删除该类别？</p>',
                    area:['300px','150px'],
                    btn:['确定','取消'],
                    btn1:function(index, layero){
                        http.post('admin/product/category/delete',{
                            id: data.id
                        },function(res){
                            if(res.code == 200){
                                layer.msg('操作成功')
                                layer.close(index)
                                getTableData()
                            }else{
                                layer.msg(res.msg)
                            }
                        })
                        
                    }
                });
            }
        })

        $('.categoryAdd').click(function(){
            // 新增
            $("#addForm .layui-form")[0].reset();
            getAllC()
            http.myOpen({
                title:'新增类别',
                content: $('#addForm'),
                area:['500px','300px'],
                btn:['确定','取消'],
                btn1:function(index, layero){
                    http.post('admin/product/category/add',{
                        categoryName: $('#addForm input[name=categoryName]').val(),
                        parentId: $('#addForm select[name=parentId]').val(),
                        openStatus: 1
                    },function(res){
                        if(res.code == 200){
                            layer.msg('操作成功')
                            layer.close(index)
                            getTableData()
                        }else{
                            layer.msg(res.msg)
                        }
                    })
                }
            })

        })

    })

</script>
</html>